package com.run.guifeng.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.codec.Encoder;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import sun.security.provider.MD5;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
@RabbitListener(queues = {"userKey"})
public class SmsUtil {

    @Autowired
    private Environment environment;

    @Value("${aliyun.guifeng.template_code}")
    private String template_code;
    @Value("${aliyun.guifeng.sign_name}")
    private String signName;
    private String param ;
    private String mobile;
    private String code;

    /**
     * 监听到有消息，将执行sendSms
     * @param map
     */
    @RabbitHandler
    public void sendSms(Map<String,String> map){
        mobile = map.get("phone");
        code = map.get("code");
        param = "{\"code\":\""+code+"\"}";
        sendSms(mobile, template_code, signName, param);
    }
    public CommonResponse sendSms(String mobile,String template_code,String signName,String param){
            String accessKeyId = environment.getProperty("aliyun.guifeng.accessKeyId");
            String accessSecret = environment.getProperty("aliyun.guifeng.accessSecret");
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putQueryParameter("PhoneNumbers", mobile);
            request.putQueryParameter("SignName", signName);
            request.putQueryParameter("TemplateCode", template_code);
            request.putQueryParameter("TemplateParam", param);
            CommonResponse response = null;
            try {
                response = client.getCommonResponse(request);
                System.out.println(response.getData());
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
            return response;
        }
}
